package concurency;

import static org.junit.Assert.assertTrue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;

public abstract class ConcurrentHarness {

	protected static final int CYCLES = 10000;
	ExecutorService executor;

	public ConcurrentHarness() {
		super();
	}

	@Before
	public void initExecutor() {
		executor = new ThreadPoolExecutor(4, 4, 5, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(CYCLES));
	}

	public void submitTask() {
		
		for (int i = 0; i < CYCLES; i++) {
			executor.submit(newTask());
		}
	}

	@After
	public void waitAllTask() throws InterruptedException {
		executor.shutdown();
		assertTrue(executor.awaitTermination(100, TimeUnit.SECONDS));
		checkResult();
	}

	abstract protected void checkResult();

	abstract protected Runnable newTask();

}